package leetcode.数组;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: levi
 * @description: https://leetcode.cn/problems/two-sum/
 * @date: 2022-9-13 13:56
 * @version: 1.0
 */
public class 两数之和_1 {

    public static void main(String[] args) {
        int[] nums = {2,7,11,15};
        int target = 9;
        int[] result1 = twoSum1(nums, target);
        for (int i : result1) {
            System.out.println(i);
        }

        int[] result2 = twoSum2(nums, target);
        for (int i : result2) {
            System.out.println(i);
        }
    }


    public static int[] twoSum1(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if(i != j && (nums[i] + nums[j]) == target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

    public static int[] twoSum2(int[] nums, int target) {
        int[] result = new int[2];
        // key 是值  value是下标
        Map<Integer,Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(target - nums[i])){
                result[0] = map.get(target - nums[i]);
                result[1] = i;
                return result;
            }else {
                map.put(nums[i],i);
            }
        }
        return result;
    }
}
